import { AudioType } from "./AudioType";


export class AudioResource {

    private static audioPool: Array<number>=new Array<number>();
    // private static bgmAudioPool: Array<number>=new Array<number>();
    private static AudioMap: Map<string, cc.AudioClip>=new Map<string, cc.AudioClip>();

    public static cacheAudioClip(clipArray: Array<cc.AudioClip>) {
        for (let index = 0; index < clipArray.length; index++) {
            const clip = clipArray[index];
            this.AudioMap.set(clip.name, clip);
        }
    }

    /**
     * 根据类型播放
     * @param audioType 
     */
    public static playByAudioType(audioType: AudioType) {
        let clip = this.AudioMap.get(audioType.toString());;
        let id = cc.audioEngine.play(clip, false, 1);
        this.audioPool.push(id);
        cc.audioEngine.setFinishCallback(id, this.onRemoveAudio.bind(this, id));
    }


    public static playByNameKey(key: string) {
        let clip = this.AudioMap.get(key);
        let id = cc.audioEngine.play(clip, false, 1);
        this.audioPool.push(id);
        cc.audioEngine.setFinishCallback(id, this.onRemoveAudio.bind(this, id));
    }

    public static pause(audioId: number) {
        cc.audioEngine.pause(audioId);
    }

    public static stop(audioId: number) {
        cc.audioEngine.stop(audioId);
    }

    public static resume(audioId: number) {
        cc.audioEngine.resume(audioId);
    }

    private static onRemoveAudio(id: number) {
        var index = this.audioPool.indexOf(id);
        if (index > -1) {
            this.audioPool.splice(index, 1);
        }
    }

    // private static onRemoveBgmAudio(id: number) {
    //     var index = this.bgmAudioPool.indexOf(id);
    //     if (index > -1) {
    //         this.bgmAudioPool.splice(index, 1);
    //     }
    // }

    /**
     * 背景音乐
     * @param audioType 
     */
    public static playBgmByType(audioType: AudioType){
        let clip = this.AudioMap.get(audioType.toString());;
        let id = cc.audioEngine.playMusic(clip, true);
        this.audioPool.push(id);
        cc.audioEngine.setFinishCallback(id, this.onRemoveAudio.bind(this, id));
    }

    //   /**
    //  * 切换
    //  * @param audioType 
    //  */
    // public static ChageBgmByType(audioType: AudioType){

    // }

//     /**
//      * 切换，并播放背景音乐
//      * @param audioType 
//      */
//    public static playAndChageBgmByType(audioType: AudioType,target:any=null){
//         let lastVolume=1;
//         let lastId= this.bgmAudioPool[0]
//         var scheduler = cc.director.getScheduler();
//         function callback(){
//             var lastBgmState = cc.audioEngine.getState(lastId);
//             if (lastBgmState && lastVolume >= 0) {
//                 lastVolume -= 0.05
//                 cc.audioEngine.setVolume(lastId, lastVolume);
//             }
//         }
//         scheduler.schedule(callback, this, 0.1, 20, 0, false);
//    }
}